package com.android.hidephotosplus.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;

public class BitmapUtils {
	// =================================================================================

	// FIXME
	private static final BitmapFactory.Options options = new BitmapFactory.Options();
	static {
		options.inSampleSize = 2;
	}

	// ================================
	public static Bitmap getThumbFromDisk(String filePath, int reqWidth,
			int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}

	// ================================

	public static Bitmap getThumbnailByPath(ContentResolver cr, String path)
			throws Exception {
		String[] projection = { MediaStore.Images.Media._ID };
		Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				projection, MediaStore.Images.Media.DATA + "=?",
				new String[] { path }, null);
		if (cursor != null && cursor.moveToFirst()) {
			long id = cursor.getLong(0);
			return getThumbnailById(cr, id);
		} else
			cursor.close();
		return null;
	}

	public static Bitmap getThumbnailById(ContentResolver cr, long idPhoto)
			throws Exception {
		return MediaStore.Images.Thumbnails.getThumbnail(cr, idPhoto,
				MediaStore.Images.Thumbnails.MINI_KIND, options);
	}

	public static Bitmap getThumbnailByIdOrgi(ContentResolver cr, long idPhoto)
			throws Exception {
		return MediaStore.Images.Thumbnails.getThumbnail(cr, idPhoto,
				MediaStore.Images.Thumbnails.MINI_KIND, null);
	}

	public static Bitmap getThumbnailVideosByPath(ContentResolver cr,
			String path) throws Exception {

		Cursor ca = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.MediaColumns._ID },
				MediaStore.MediaColumns.DATA + "=?", new String[] { path },
				null);
		if (ca != null && ca.moveToFirst()) {
			int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
			ca.close();
			return MediaStore.Video.Thumbnails.getThumbnail(cr, id,
					MediaStore.Video.Thumbnails.MINI_KIND, options);
		}

		ca.close();
		return null;
	}

	public static Bitmap getThumbnailVideosById(ContentResolver cr, long idVideo) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		return MediaStore.Video.Thumbnails.getThumbnail(cr, idVideo,
				MediaStore.Video.Thumbnails.MINI_KIND, options);
	}

	public static String getImageUri(Context inContext, Bitmap inImage) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
		String path = Images.Media.insertImage(inContext.getContentResolver(),
				inImage, "Title", null);
		return path;
	}

	// create Thumbnail Video
	public static Bitmap createThumbnailVideos(String path) {
		return ThumbnailUtils.createVideoThumbnail(path,
				MediaStore.Images.Thumbnails.MINI_KIND);
	}

	public static Bitmap decodeFile(String path, int maxWidth, int maxHeight) {
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			o.inSampleSize = calculateInSampleSize(o, maxHeight, maxWidth);
			BitmapFactory.decodeFile(path, o);

			int scale = 1;
			if (o.outHeight > maxWidth || o.outWidth > maxHeight) {
				scale = (int) Math.pow(
						2,
						(int) Math.round(Math.log(Math.max(maxWidth
								/ (double) o.outWidth, maxHeight
								/ (double) o.outHeight))
								/ Math.log(0.5)));

				if (scale == 1) {
					scale = 2;
				}
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;

			return BitmapFactory.decodeFile(path, o2);

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			Log.e("OutOfMemoryError KEN.....", e.toString());
			return null;
		}
	}

//	public static Bitmap decodeFile(ContentResolver contentResolver, String path) {
//
//		Uri uri = Uri.fromFile(new File(path));
//		InputStream in = null;
//		try {
//			final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
//			in = contentResolver.openInputStream(uri);
//
//			// Decode image size
//			BitmapFactory.Options o = new BitmapFactory.Options();
//			o.inJustDecodeBounds = true;
//			BitmapFactory.decodeStream(in, null, o);
//			in.close();
//
//			int scale = 1;
//			while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
//				scale++;
//			}
//
//			Bitmap b = null;
//			in = contentResolver.openInputStream(uri);
//			if (scale > 1) {
//				scale--;
//				// scale to max possible inSampleSize that still yields an image
//				// larger than target
//				o = new BitmapFactory.Options();
//				o.inSampleSize = scale;
//				b = BitmapFactory.decodeStream(in, null, o);
//
//				// resize to desired dimensions
//				int height = b.getHeight();
//				int width = b.getWidth();
//
//				double y = Math.sqrt(IMAGE_MAX_SIZE
//						/ (((double) width) / height));
//				double x = (y / height) * width;
//
//				Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,(int) y, true);
//				b.recycle();
//				b = scaledBitmap;
//
//				System.gc();
//			} else {
//				b = BitmapFactory.decodeStream(in);
//			}
//			in.close();
//			return b;
//		} catch (IOException e) {
//			Log.e("OutOfMemoryError KEN.....", e.toString());
//			return null;
//		}
//
//	}
}